﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommonTagTime.PagerControl;
using CommonTagTime.Business;
using CommonTagTime.ModelObject;
using CommonTagTime;
using Resources;

public partial class admin_ProductList : SitePage
{
    #region ViewState
    public int count = 0;
    public string paraURL
    {
        get
        {
            object o = ViewState["paraURL"];
            if (o != null) return (string)o;
            return string.Empty;
        }
        set { ViewState["paraURL"] = value; }

    }
    public int F_PageIndex
    {

        get
        {

            object o = ViewState["F_PageIndex"];

            if (o != null) return (int)o;

            return 0;

            //a default

        }

        set { ViewState["F_PageIndex"] = value; }

    }
    public int F_PageSize
    {

        get
        {

            object o = ViewState["F_PageSize"];

            if (o != null) return (int)o;

            return 0;

            //a default

        }

        set { ViewState["F_PageSize"] = value; }

    }
    public string F_SortField
    {

        get
        {
            object o = ViewState["F_SortField"];
            if (o != null) return (string)o;
            return string.Empty;
        }

        set { ViewState["F_SortField"] = value; }

    }
    public string F_SortExpression
    {

        get
        {
            object o = ViewState["F_SortExpression"];
            if (o != null) return (string)o;
            return string.Empty;
        }

        set { ViewState["F_SortExpression"] = value; }

    }
    #endregion

    #region Init,Loads
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            clsBindControl.BindBooleanCombobox(F_ddlIsAvtive);
            clsBindControl.BindBooleanCombobox(F_ddlIsNew);
            LoadParent();
            Getparamater();
            LoadData();
        }
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);     
    }
    #endregion

    #region Events
    protected void Pager2_PageIndexChanging(object obj, PageIndexChangeEventArgs e)
    {
        this.F_PageIndex = e.PageIndex;
        LoadData();
    }
    protected void Pager2_PageSizeChanging(object obj, PageSizeChangeEventArgs e)
    {
        this.F_PageIndex = 1;
        this.F_PageSize=Pager2.PageSize = Pager1.PageSize = e.PageSize;
        LoadData();
    }
    protected void rptData_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Product objProdjuct = (Product)e.Item.DataItem;
            if (objProdjuct == null)
                return;
            hidProductID.Value += objProdjuct.ProductID.ToString() + ";";


            //image button IsActive
            ImageButton imgButton = (ImageButton)e.Item.FindControl("imbActive");
            imgButton.CommandArgument = objProdjuct.ProductID.ToString();
            if (objProdjuct.IsActive == true)
            {
                imgButton.ImageUrl = clsString.ACTIVE_IMAGE_URL;
                imgButton.ToolTip = Resources.Resource.TIP_DEACTIVE;
                imgButton.CommandName = "DeActive";
            }
            else
            {
                imgButton.ImageUrl = clsString.DEACTIVE_IMAGE_URL;
                imgButton.ToolTip = Resources.Resource.TIP_ACTIVE;
                imgButton.CommandName = "Active";
            }
            //image button IsNew
            imgButton = (ImageButton)e.Item.FindControl("imbIsNew");
            imgButton.CommandArgument = objProdjuct.ProductID.ToString();
            if (objProdjuct.IsNew == true)
            {
                imgButton.ImageUrl = clsString.ACTIVE_IMAGE_URL;
                imgButton.ToolTip = Resources.Resource.TIP_REMOVENEW;
                imgButton.CommandName = "RemoveNew";
            }
            else
            {
                imgButton.ImageUrl = clsString.DEACTIVE_IMAGE_URL;
                imgButton.ToolTip = Resources.Resource.TIP_SETNEW;
                imgButton.CommandName = "SetNew";
            }

            //image button
            imgButton = (ImageButton)e.Item.FindControl("imbDelete");
            imgButton.ToolTip = Resources.Resource.TIP_DELETE;
            imgButton.Attributes.Add("onclick", "return confirm('" + Resources.Resource.MSG_CONFIRM_DELETE + "');");
            imgButton.CommandArgument = objProdjuct.ProductID.ToString();
            imgButton.ImageUrl = clsString.DELETE_IMAGE_URL;
            //Related Item
            Literal ltrRelatedItem = (Literal)e.Item.FindControl("ltrRelatedItem");
            ltrRelatedItem.Text = "<a href='AddRelatedItem.aspx?id=" + objProdjuct.ProductID + "&" + paraURL + "' class='related'>" + objProdjuct.RelatedItemCount + "</a>";

            //MSDS Item
            ltrRelatedItem = (Literal)e.Item.FindControl("ltrMSDS");
            ltrRelatedItem.Text = "<a href='DocumentList.aspx?F_txtSKU=" + objProdjuct.SKU + "' class='related'>" + objProdjuct.MSDSCount + "</a>";

        }

    }
    protected void rptData_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "SortOrder")
        {
            SortList(e.CommandArgument.ToString());

        }
        else
        {
            int id = clsConvert.Int(e.CommandArgument.ToString());
            switch (e.CommandName)
            {
                case "Active":
                    {
                        Active(id);
                        break;
                    }
                case "DeActive":
                    {
                        DeActive(id);
                        break;
                    }

                case "SetNew":
                    {
                        SetNew(id);
                        break;
                    }
                case "RemoveNew":
                    {
                        RemoveNew(id);
                        break;
                    }

                case "Delete":
                    {
                        Delete(id);
                        LoadData();
                        break;
                    }
            }
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        this.F_PageIndex = 1;
        LoadData();
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        ProductCollection lstCate = new ProductCollection();
        string[] arr = hidProductIDSelect.Value.Split(';');
        for (int i = 0; i < arr.Length; i++)
        {
            if (arr[i].ToString() != string.Empty)
            {
                int pID=clsConvert.Int(arr[i].ToString());
                Delete(pID);         
            }
        }       
        LoadData();
    }
    private void LoadParent()
    {
        Category objCondition = new Category();
        objCondition.OrderBy = busCategory.SORTORDER;
        objCondition.OrderDirection = "ASC";
        objCondition.Condition = " ParentId is null and Type=" + (byte)enmCategoryType.Product;
        objCondition.CurrentPage = 1;
        objCondition.PageSize = int.MaxValue;
        busCategory objBus = new busCategory();
        CategoryCollection lstLevel1 = objBus.List(objCondition);//only return one object       
        if (lstLevel1 != null && lstLevel1.Count > 0)
        {
            foreach (Category objData in lstLevel1)
            {
                AddNode(objData);
            }

        }
        //  if (addEmpty)
        F_drlCategory.Items.Insert(0, new ListItem("- - -", string.Empty));
        F_drlCategory.SelectedValue = clsQueryString.GetString("cateId");
    }
    private void AddNode(Category objData)
    {
        string prefix = string.Empty;
        for (int i = 2; i <= objData.Level; i++)
        {
            prefix += "--";
        }
        F_drlCategory.Items.Add(new ListItem(prefix + objData.Name, objData.CategoryID.ToString()));
        CategoryCollection lstChild = GetChild(objData);
        if (lstChild != null && lstChild.Count > 0)
        {
            foreach (Category objChild in lstChild)
            {
                AddNode(objChild);
            }
        }
    }
    private CategoryCollection GetChild(Category objData)
    {
        Category objCondition = new Category();
        objCondition.OrderBy = busCategory.SORTORDER;
        objCondition.OrderDirection = "ASC";
        objCondition.Condition = " ParentId=" + objData.CategoryID + " and Type=" + (byte)enmCategoryType.Product;
        objCondition.CurrentPage = 1;
        objCondition.PageSize = int.MaxValue;
        busCategory objBus = new busCategory();
        CategoryCollection lstResult = objBus.List(objCondition);
        return lstResult;
    }
    protected void btnAddNew_Click(object sender, EventArgs e)
    {
        Response.Redirect("ProductDetail.aspx");
    }

    #endregion

    #region Methods
    private void SortList(string F_SortField)
    {
        if (this.F_SortField == F_SortField)
        {
            if (this.F_SortExpression == "ASC")
                this.F_SortExpression = "DESC";
            else this.F_SortExpression = "ASC";
        }
        else
        {
            this.F_SortField = F_SortField;
            this.F_SortExpression = "ASC";
        }
        LoadData();
    }
    private void Active(int id)
    {
        busProduct _busProduct = new busProduct();
        if (id > 0 && _busProduct.Active(id))
            LoadData();
    }
    private void DeActive(int id)
    {
        busProduct _busProduct = new busProduct();
        if (id > 0 && _busProduct.DeActive(id))
            LoadData();
    }
    private void SetNew(int id)
    {
        busProduct _busProduct = new busProduct();
        if (id > 0 && _busProduct.SetNew(id))
            LoadData();
    }
    private void RemoveNew(int id)
    {
        busProduct _busProduct = new busProduct();
        if (id > 0 && _busProduct.RemoveNew(id))
            LoadData();
    }
    private void Delete(int id)
    {
        busProduct _busProduct = new busProduct();
        busImageProduct objBus = new busImageProduct();
        ImageProductCollection lstImage = objBus.GetListByProductID(id);
        if (id > 0 && _busProduct.Delete(id))
        {                       
            if (lstImage != null && lstImage.Count > 0)
            {
                foreach (ImageProduct objImage in lstImage)
                {                   
                    if (objImage != null)
                        DeleteImage(objImage.FileName);
                }
            }             
        }
    }
    private void DeleteImage(string _orgImageFileName)
    {
        string path = Server.MapPath(clsConfigData.DEFAULT_UPLOAD_PRODUCT_IMAGES_FOLDER);
        clsFile.DeleteFile(path + _orgImageFileName);
        path = Server.MapPath(clsConfigData.DEFAULT_UPLOAD_PRODUCT_THUMB_FOLDER);
        clsFile.DeleteFile(path + _orgImageFileName);
        path = Server.MapPath(clsConfigData.DEFAULT_UPLOAD_PRODUCT_FOLDER);
        clsFile.DeleteFile(path + _orgImageFileName);
        path = Server.MapPath(clsConfigData.DEFAULT_UPLOAD_PRODUCT_SMALL_FOLDER);
        clsFile.DeleteFile(path + _orgImageFileName);
        path = Server.MapPath(clsConfigData.DEFAULT_UPLOAD_PRODUCT_LARGE_FOLDER);
        clsFile.DeleteFile(path + _orgImageFileName);
    }
    private void LoadData()
    {
        paraURL = GetPageParams(FilterFieldType.All);
        hidProductID.Value = string.Empty;

        //get Condition
        Product objProduct = new Product();
        objProduct.CurrentPage = this.F_PageIndex;
        objProduct.OrderBy = this.F_SortField;
        objProduct.OrderDirection = this.F_SortExpression;
        objProduct.PageSize = Pager1.PageSize;
        objProduct.Condition = GetCondition();

        busProduct _busProduct = new busProduct();
        ProductCollection lstResult = _busProduct.List(objProduct);

        if (lstResult != null && lstResult.Count > 0)
        {
            count = lstResult.Count;
            rptData.DataSource = lstResult;

            divGrid.Visible = true;
            divEmplty.Visible = false;
        }
        else
        {
            rptData.DataSource = null;
            divGrid.Visible = false;

            divEmplty.Visible = true;
            divEmplty.InnerHtml = Resource.MSG_EMPTY;
        }

        rptData.DataBind();

        Pager1.SetPaging(this.F_PageIndex, count, objProduct.TotalRecords);
        Pager2.SetPaging(this.F_PageIndex, count, objProduct.TotalRecords);       
    }
    private string GetConditionCate()
    {
        string conditionCate = string.Empty;
        if (F_drlCategory.SelectedValue != string.Empty)
        {
            busProductCategory objBus = new busProductCategory();
            ProductCategoryCollection lstCate = objBus.GetListByCategoryID(clsConvert.Int(F_drlCategory.SelectedValue.ToString()));
            if (lstCate != null)
            {
                foreach (ProductCategory objCate in lstCate)
                {
                    conditionCate += objCate.ProductID + ",";
                }
            }
            if (conditionCate != string.Empty)
            {
                conditionCate = conditionCate.Substring(0, conditionCate.Length - 1);
            }
            return conditionCate;
        }
        return string.Empty;
    }
    private void Getparamater()
    {
        F_drlCategory.SelectedValue = clsQueryString.GetString("F_drlCategory");
        F_txtName.Text = clsQueryString.GetString("F_txtName");
        F_txtSKU.Text = clsQueryString.GetString("F_txtSKU");
        this.F_SortField = clsQueryString.GetString("F_SortField");
        if (this.F_SortField == string.Empty)
            this.F_SortField = busProduct.CREATEDDATE;
        this.F_SortExpression = clsQueryString.GetString("F_SortExpression");
        if (this.F_SortExpression == string.Empty)
            this.F_SortExpression = "DESC";
        F_PageIndex = clsQueryString.GetInt("F_PageIndex");
        F_PageSize = clsQueryString.GetInt("F_PageSize");
        if (F_PageSize < 1)
            F_PageSize = clsConfigData.DEFAULT_ADMIN_PAGE_SIZE;
        if (F_PageIndex < 1)
            F_PageIndex = 1;
        this.Pager2.PageSize = this.Pager1.PageSize = F_PageSize;
        F_ddlIsAvtive.SelectedValue = clsQueryString.GetString("F_ddlIsAvtive");
        F_ddlIsNew.SelectedValue = clsQueryString.GetString("F_ddlIsNew");             
    }
    private string GetCondition()
    {
        string result = "1=1";
        string cateId = string.Empty;
        if (F_txtSKU.Text != string.Empty)
            result += " and p.SKU='" + F_txtSKU.Text + "'";
        if (F_txtName.Text != string.Empty)
            result += " and p.Name like N'%" + F_txtName.Text + "%'";
        if (F_ddlIsAvtive.SelectedValue != string.Empty)
            result += " and p.IsActive=" + F_ddlIsAvtive.SelectedValue.ToString();
        if (F_ddlIsNew.SelectedValue != string.Empty)
            result += " and p.IsNew=" + F_ddlIsNew.SelectedValue.ToString();
        string conditionCate = GetConditionCate();
        if (F_drlCategory.SelectedValue != string.Empty)
        {
            if (conditionCate != string.Empty)
                result = result + " and p.ProductID in(" + conditionCate + ") ";
            else result = result + " and p.ProductID<0 ";
        }
        return result;
    }
    #endregion   
}